const path = require('path');
const Components = require('unplugin-vue-components/webpack');
const {
    ElementPlusResolver
} = require('unplugin-vue-components/resolvers');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

// 路径
function resolve(dir) {
    return path.join(__dirname, dir);
}

module.exports = {
    publicPath: '/', //应用包的基本URL
    assetsDir: 'static', //放置静态资源
    outputDir: path.resolve(__dirname, './dist'), // 输出文件目录
    lintOnSave: true, // eslint-loader 是否在保存的时候检查
    productionSourceMap: false, // 是否打包.map
    devServer: {
        port: 8000, // 本地端口
        // proxy: process.env.VUE_APP_HOST, //请求代理
        proxy: {
            '/': {
                target: process.env.VUE_APP_HOST, // 代理地址
                changeOrigin: true, // 允许跨域
                pathRewrite: {
                    '^/': ''
                } // 重写路径
            }
        },
        disableHostCheck: true
    },
    chainWebpack: (config) => {
        config.resolve.alias
            .set('@', resolve('src'))
            .set('P', resolve('public'))
            .set('api', resolve('src/global/api'));
        if (process.env.NODE_ENV === 'production') {
            config.output.filename('static/js/[name].[chunkhash:6].js');
            config.output.chunkFilename('static/js/[name].[chunkhash:6].js');
        }
    },
    configureWebpack: {
        plugins: [
            // 按需导入ui
            require('unplugin-vue-components/webpack')({}),
            Components({
                resolvers: [ElementPlusResolver()]
            }),
            new UglifyJsPlugin({
                uglifyOptions: {
                    compress: {
                        drop_console: true,
                        pure_funcs: ['console.log']
                    }
                }
            }),
            // css压缩
            new OptimizeCssAssetsWebpackPlugin({
                assetNameRegExp: /\.css$/g, // 用来匹配文件名称的正则表达式
                cssProcessor: require('cssnano') // 引入cssnano配置压缩选项
            }),
            // gzip压缩
            new CompressionPlugin({
                filename: "[path].gz",
                // 压缩算法
                algorithm: "gzip",
                // 匹配文件
                test: /\.js$|\.css$|\.html$/,
                // 压缩超多此大小的文件，以字节为单位
                threshold: 10240,
                minRatio: 0.8,
                // 删除原始文件只保留压缩后的文件
                deleteOriginalAssets: false
            })
        ]
    }
};